[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  22. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. import type { EditorConfig } from '~/interfaces/editor-settings';
  25. import type { IPageGrantData } from '~/interfaces/page';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { PageModel, PageDocument } from '~/server/models/page';
  28. import type { PageRedirectModel } from '~/server/models/page-redirect';
  29. import {
  30. useCurrentUser,
  31. useIsForbidden, useIsSharedUser,
  32. useIsEnabledStaleNotification, useIsIdenticalPath,
  33. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  34. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  35. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  36. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  37. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  38. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  39. } from '~/stores/context';
  40. import { useEditingMarkdown } from '~/stores/editor';
  41. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  42. import {
  43. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  44. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  45. } from '~/stores/page';
  46. import { useRedirectFrom } from '~/stores/page-redirect';
  47. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  48. import { useSelectedGrant } from '~/stores/ui';
  49. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  50. import loggerFactory from '~/utils/logger';
  51. import { BasicLayout } from '../components/Layout/BasicLayout';
  52. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  53. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  54. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  55. import type { NextPageWithLayout } from './_app.page';
  56. import type { CommonProps } from './utils/commons';
  57. import {
  58. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  59. } from './utils/commons';
  60. declare global {
  61. // eslint-disable-next-line vars-on-top, no-var
  62. var globalEmitter: EventEmitter;
  63. }
  64. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  65. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  67. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  68. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  69. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  70. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  71. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  72. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  73. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  74. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  75. const logger = loggerFactory('growi:pages:all');
  76. const {
  77. isPermalink: _isPermalink, isCreatablePage,
  78. } = pagePathUtils;
  79. const { removeHeadingSlash } = pathUtils;
  80. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  81. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  82. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  83. {
  84. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  85. return v?.data != null
  86. && v?.data.toObject != null
  87. && v?.meta != null
  88. && isIPageInfoForEntity(v.meta);
  89. },
  90. serialize: (v) => {
  91. return {
  92. data: superjson.stringify(v.data.toObject()),
  93. meta: superjson.stringify(v.meta),
  94. };
  95. },
  96. deserialize: (v) => {
  97. return {
  98. data: superjson.parse(v.data),
  99. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  100. };
  101. },
  102. },
  103. 'IPageToShowRevisionWithMetaTransformer',
  104. );
  105. // GrowiContextualSubNavigation for NOT shared page
  106. type GrowiContextualSubNavigationProps = {
  107. isLinkSharingDisabled: boolean,
  108. }
  109. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  110. const { isLinkSharingDisabled } = props;
  111. const { data: currentPage } = useSWRxCurrentPage();
  112. return (
  113. <div data-testid="grw-contextual-sub-nav">
  114. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  115. </div>
  116. );
  117. };
  118. type Props = CommonProps & {
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatable: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isEnabledMarp: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. hackmdUri: string,
  141. noCdn: string,
  142. // highlightJsStyle: string,
  143. isAllReplyShown: boolean,
  144. isContainerFluid: boolean,
  145. editorConfig: EditorConfig,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. skipSSR: boolean,
  154. ssrMaxRevisionBodyLength: number,
  155. grantData?: IPageGrantData,
  156. rendererConfig: RendererConfig,
  157. };
  158. const Page: NextPageWithLayout<Props> = (props: Props) => {
  159. // register global EventEmitter
  160. if (isClient() && window.globalEmitter == null) {
  161. window.globalEmitter = new EventEmitter();
  162. }
  163. const router = useRouter();
  164. useCurrentUser(props.currentUser ?? null);
  165. // commons
  166. useEditorConfig(props.editorConfig);
  167. useCsrfToken(props.csrfToken);
  168. useGrowiCloudUri(props.growiCloudUri);
  169. // page
  170. useIsContainerFluid(props.isContainerFluid);
  171. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  172. useIsForbidden(props.isForbidden);
  173. useIsNotCreatable(props.isNotCreatable);
  174. useRedirectFrom(props.redirectFrom ?? null);
  175. useIsSharedUser(false); // this page cann't be routed for '/share'
  176. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  177. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  178. useIsSearchPage(false);
  179. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  180. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  181. useIsSearchServiceReachable(props.isSearchServiceReachable);
  182. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  183. useIsSlackConfigured(props.isSlackConfigured);
  184. // useIsMailerSetup(props.isMailerSetup);
  185. useIsAclEnabled(props.isAclEnabled);
  186. // useHasSlackConfig(props.hasSlackConfig);
  187. useHackmdUri(props.hackmdUri);
  188. // useNoCdn(props.noCdn);
  189. useDefaultIndentSize(props.adminPreferredIndentSize);
  190. useIsIndentSizeForced(props.isIndentSizeForced);
  191. useDisableLinkSharing(props.disableLinkSharing);
  192. useRendererConfig(props.rendererConfig);
  193. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  194. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  195. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  196. useIsAllReplyShown(props.isAllReplyShown);
  197. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  198. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  199. const { pageWithMeta } = props;
  200. const pageId = pageWithMeta?.data._id;
  201. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  202. const revisionBody = pageWithMeta?.data.revision?.body;
  203. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  204. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  205. useCurrentPathname(props.currentPathname);
  206. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  207. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  208. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  209. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  210. const { mutate: mutateIsNotFound } = useIsNotFound();
  211. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  212. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  213. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  214. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  215. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  216. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  217. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  218. useSetupGlobalSocket();
  219. useSetupGlobalSocketForPage(pageId);
  220. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  221. // Store initial data (When revisionBody is not SSR)
  222. useEffect(() => {
  223. if (!props.skipSSR) {
  224. return;
  225. }
  226. if (currentPageId != null && !props.isNotFound) {
  227. const mutatePageData = async() => {
  228. const pageData = await mutateCurrentPage();
  229. mutateEditingMarkdown(pageData?.revision.body);
  230. };
  231. // If skipSSR is true, use the API to retrieve page data.
  232. // Because pageWIthMeta does not contain revision.body
  233. mutatePageData();
  234. }
  235. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  236. // sync grant data
  237. useEffect(() => {
  238. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  239. mutateSelectedGrant(grantDataToApply);
  240. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  241. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  242. useEffect(() => {
  243. const decodedURI = decodeURI(window.location.pathname);
  244. if (isClient() && decodedURI !== props.currentPathname) {
  245. const { search, hash } = window.location;
  246. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  247. }
  248. }, [props.currentPathname, router]);
  249. // initialize mutateEditingMarkdown only once per page
  250. // need to include useCurrentPathname not useCurrentPagePath
  251. useEffect(() => {
  252. if (props.currentPathname != null) {
  253. mutateEditingMarkdown(revisionBody);
  254. }
  255. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  256. useEffect(() => {
  257. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  258. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  259. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  260. useEffect(() => {
  261. mutateCurrentPageId(pageId ?? null);
  262. }, [mutateCurrentPageId, pageId]);
  263. useEffect(() => {
  264. mutateIsNotFound(props.isNotFound);
  265. }, [mutateIsNotFound, props.isNotFound]);
  266. useEffect(() => {
  267. mutateIsLatestRevision(props.isLatestRevision);
  268. }, [mutateIsLatestRevision, props.isLatestRevision]);
  269. useEffect(() => {
  270. mutateTemplateTagData(props.templateTagData);
  271. }, [props.templateTagData, mutateTemplateTagData]);
  272. useEffect(() => {
  273. mutateTemplateBodyData(props.templateBodyData);
  274. }, [props.templateBodyData, mutateTemplateBodyData]);
  275. const title = generateCustomTitleForPage(props, pagePath);
  276. return (
  277. <>
  278. <Head>
  279. <title>{title}</title>
  280. </Head>
  281. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  282. <header className="py-0 position-relative">
  283. <div id="grw-subnav-container">
  284. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  285. </div>
  286. </header>
  287. <div className="d-edit-none">
  288. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  289. </div>
  290. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  291. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  292. <DisplaySwitcher
  293. pageView={(
  294. <PageView
  295. pagePath={pagePath}
  296. initialPage={pageWithMeta?.data}
  297. rendererConfig={props.rendererConfig}
  298. />
  299. )}
  300. />
  301. <PageStatusAlert />
  302. </div>
  303. </>
  304. );
  305. };
  306. type LayoutProps = Props & {
  307. children?: ReactNode
  308. }
  309. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  310. const className = useEditorModeClassName();
  311. // init sidebar config with UserUISettings and sidebarConfig
  312. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  313. return (
  314. <BasicLayout className={className}>
  315. {children}
  316. </BasicLayout>
  317. );
  318. };
  319. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  320. return (
  321. <>
  322. <GrowiPluginsActivator />
  323. <DrawioViewerScript />
  324. <Layout {...page.props}>
  325. {page}
  326. </Layout>
  327. <UnsavedAlertDialog />
  328. <DescendantsPageListModal />
  329. <DrawioModal />
  330. <HandsontableModal />
  331. <QuestionnaireModalManager />
  332. <TemplateModal />
  333. <LinkEditModal />
  334. </>
  335. );
  336. };
  337. function getPageIdFromPathname(currentPathname: string): string | null {
  338. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  339. }
  340. class MultiplePagesHitsError extends ExtensibleCustomError {
  341. pagePath: string;
  342. constructor(pagePath: string) {
  343. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  344. this.pagePath = pagePath;
  345. }
  346. }
  347. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  348. const { model: mongooseModel } = await import('mongoose');
  349. const req: CrowiRequest = context.req as CrowiRequest;
  350. const { crowi } = req;
  351. const { revisionId } = req.query;
  352. const Page = crowi.model('Page') as PageModel;
  353. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  354. const { pageService, configManager } = crowi;
  355. let currentPathname = props.currentPathname;
  356. const pageId = getPageIdFromPathname(currentPathname);
  357. const isPermalink = _isPermalink(currentPathname);
  358. const { user } = req;
  359. if (!isPermalink) {
  360. // check redirects
  361. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  362. if (chains != null) {
  363. // overwrite currentPathname
  364. currentPathname = chains.end.toPath;
  365. props.currentPathname = currentPathname;
  366. // set redirectFrom
  367. props.redirectFrom = chains.start.fromPath;
  368. }
  369. // check whether the specified page path hits to multiple pages
  370. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  371. if (count > 1) {
  372. throw new MultiplePagesHitsError(currentPathname);
  373. }
  374. }
  375. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  376. const page = pageWithMeta?.data as unknown as PageDocument;
  377. // add user to seen users
  378. if (page != null && user != null) {
  379. await page.seen(user);
  380. }
  381. // populate & check if the revision is latest
  382. if (page != null) {
  383. page.initLatestRevisionField(revisionId);
  384. props.isLatestRevision = page.isLatestRevision();
  385. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  386. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  387. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  388. }
  389. if (page == null && user != null) {
  390. const templateData = await Page.findTemplate(props.currentPathname);
  391. if (templateData != null) {
  392. props.templateTagData = templateData.templateTags as string[];
  393. props.templateBodyData = templateData.templateBody as string;
  394. }
  395. // apply parent page grant, without groups that user isn't related to
  396. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  397. if (ancestor != null) {
  398. const userRelatedGrantedGroups = await pageService.getUserRelatedGrantedGroups(ancestor, user);
  399. props.grantData = {
  400. grant: ancestor.grant,
  401. grantedGroups: userRelatedGrantedGroups.map((group) => {
  402. return {
  403. id: group.item._id,
  404. name: group.item.name,
  405. type: group.type,
  406. };
  407. }),
  408. };
  409. }
  410. }
  411. props.pageWithMeta = pageWithMeta;
  412. }
  413. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  414. const req: CrowiRequest = context.req as CrowiRequest;
  415. const { crowi } = req;
  416. const Page = crowi.model('Page') as PageModel;
  417. const { currentPathname } = props;
  418. const pageId = getPageIdFromPathname(currentPathname);
  419. const isPermalink = _isPermalink(currentPathname);
  420. const page = props.pageWithMeta?.data;
  421. if (props.isIdenticalPathPage) {
  422. props.isNotCreatable = true;
  423. }
  424. else if (page == null) {
  425. props.isNotFound = true;
  426. props.isNotCreatable = !isCreatablePage(currentPathname);
  427. // check the page is forbidden or just does not exist.
  428. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  429. props.isForbidden = count > 0;
  430. }
  431. else {
  432. props.isNotFound = page.isEmpty;
  433. props.isNotCreatable = false;
  434. props.isForbidden = false;
  435. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  436. if (isPermalink && page.isEmpty) {
  437. props.currentPathname = page.path;
  438. }
  439. // /path/to/page ==> /62a88db47fed8b2d94f30000
  440. if (!isPermalink && !page.isEmpty) {
  441. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  442. if (!isToppage) {
  443. props.currentPathname = `/${page._id}`;
  444. }
  445. }
  446. }
  447. }
  448. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  449. // const req: CrowiRequest = context.req as CrowiRequest;
  450. // const { crowi } = req;
  451. // const UserModel = crowi.model('User');
  452. // if (isUserPage(props.currentPagePath)) {
  453. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  454. // if (user != null) {
  455. // props.pageUser = JSON.stringify(user.toObject());
  456. // }
  457. // }
  458. // }
  459. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  460. const req: CrowiRequest = context.req as CrowiRequest;
  461. const { crowi } = req;
  462. const {
  463. searchService, configManager, aclService,
  464. } = crowi;
  465. props.isSearchServiceConfigured = searchService.isConfigured;
  466. props.isSearchServiceReachable = searchService.isReachable;
  467. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  468. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  469. // props.isMailerSetup = mailService.isMailerSetup;
  470. props.isAclEnabled = aclService.isAclEnabled();
  471. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  472. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  473. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  474. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  475. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  476. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  477. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  478. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  479. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  480. props.editorConfig = {
  481. upload: {
  482. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  483. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  484. },
  485. };
  486. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  487. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  488. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  489. props.rendererConfig = {
  490. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  491. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  492. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  493. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  494. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  495. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  496. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  497. // XSS Options
  498. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  499. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  500. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  501. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  502. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  503. };
  504. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  505. }
  506. /**
  507. * for Server Side Translations
  508. * @param context
  509. * @param props
  510. * @param namespacesRequired
  511. */
  512. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  513. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  514. props._nextI18Next = nextI18NextConfig._nextI18Next;
  515. }
  516. const getAction = (props: Props): SupportedActionType => {
  517. if (props.isNotCreatable) {
  518. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  519. }
  520. if (props.isForbidden) {
  521. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  522. }
  523. if (props.isNotFound) {
  524. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  525. }
  526. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  527. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  528. }
  529. return SupportedAction.ACTION_PAGE_VIEW;
  530. };
  531. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  532. const req = context.req as CrowiRequest;
  533. const { user } = req;
  534. const result = await getServerSideCommonProps(context);
  535. // check for presence
  536. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  537. if (!('props' in result)) {
  538. throw new Error('invalid getSSP result');
  539. }
  540. const props: Props = result.props as Props;
  541. if (props.redirectDestination != null) {
  542. return {
  543. redirect: {
  544. permanent: false,
  545. destination: props.redirectDestination,
  546. },
  547. };
  548. }
  549. if (user != null) {
  550. props.currentUser = user.toObject();
  551. }
  552. try {
  553. await injectPageData(context, props);
  554. }
  555. catch (err) {
  556. if (err instanceof MultiplePagesHitsError) {
  557. props.isIdenticalPathPage = true;
  558. }
  559. else {
  560. throw err;
  561. }
  562. }
  563. await injectRoutingInformation(context, props);
  564. injectServerConfigurations(context, props);
  565. await injectNextI18NextConfigurations(context, props, ['translation']);
  566. addActivity(context, getAction(props));
  567. return {
  568. props,
  569. };
  570. };
  571. export default Page;